package com.huiminpay.merchant.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.huiminpay.common.cache.domain.BusinessException;
import com.huiminpay.common.cache.domain.CommonErrorCode;
import com.huiminpay.common.cache.util.RandomUuidUtil;
import com.huiminpay.merchant.api.AppService;
import com.huiminpay.merchant.convert.AppCovert;
import com.huiminpay.merchant.dto.AppDTO;
import com.huiminpay.merchant.entity.App;
import com.huiminpay.merchant.entity.Merchant;
import com.huiminpay.merchant.mapper.AppMapper;
import com.huiminpay.merchant.mapper.MerchantMapper;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

import javax.security.auth.login.AppConfigurationEntry;
import java.util.List;

@Service
public class AppServiceImpl implements AppService {
    @Autowired
    private MerchantMapper merchantMapper;
    @Autowired
    private AppMapper appMapper;
    @Override
    public AppDTO createApp(Long merchantId, AppDTO appDto) throws BusinessException {
        Merchant merchant = merchantMapper.selectById(merchantId);
        if (merchant==null){
            throw new BusinessException(CommonErrorCode.E_200002);
        }
        if (!"2".equals(merchant.getAuditStatus())){
            throw new BusinessException(CommonErrorCode.E_200003);
        }
        if (isExistAppName(appDto.getAppName())){
            throw new BusinessException(CommonErrorCode.E_200004);
        }
        appDto.setAppId(RandomUuidUtil.getUUID());
        appDto.setMerchantId(merchant.getId());
        App app = AppCovert.INSTANCE.dto2entity(appDto);
        appMapper.insert(app);
        return AppCovert.INSTANCE.entity2dto(app);
    }
    public boolean isExistAppName(String appName){
        Integer num = appMapper.selectCount(new LambdaQueryWrapper<App>().eq(App::getAppName, appName));
        return num>0;
    }
    @Override
    public List<AppDTO> queryAppByMerchantId(Long merchantId) throws BusinessException {
        List<App> apps = appMapper.selectList(new LambdaQueryWrapper<App>().eq(App::getMerchantId, merchantId));
        List<AppDTO> appDTOS = AppCovert.INSTANCE.listEntity2dto(apps);
        return appDTOS;
    }
    @Override
    public AppDTO selectAppById(String id) throws BusinessException {
        App app = appMapper.selectOne(new LambdaQueryWrapper<App>().eq(App::getAppId, id));
        return AppCovert.INSTANCE.entity2dto(app);
    }

    @Override
    public Boolean queryAppInMerchant(String appId, Long merchantId) {
        LambdaQueryWrapper<App> wrapper = new LambdaQueryWrapper<App>().
                eq(App::getAppId, appId).eq(App::getMerchantId, merchantId);
        Integer num = appMapper.selectCount(wrapper);

        return num>0;
    }


}
